package com.fernfx.xingtan.contacts.ui;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.base.BaseActivity;
import com.fernfx.xingtan.contacts.contract.MessageChatContract;
import com.fernfx.xingtan.user.AccountManager;
import com.fernfx.xingtan.utils.LogUtils;
import com.fernfx.xingtan.utils.OtherUtil;

import java.util.Locale;

import io.rong.imkit.RongIM;
import io.rong.imkit.fragment.ConversationFragment;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;

/**
 * Created by admin on 2018/8/6.
 */

public class MessageChatActivity extends BaseActivity implements MessageChatContract.View {
    private Conversation.ConversationType mConversationType;
    private String mTargetId;
    boolean isFromPush = false;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_chat_message;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {
        //获取显示的名称
        Intent intent = getIntent();
        String title = intent.getData().getQueryParameter("title");
        if (!TextUtils.isEmpty(title)) {
            setToolbarTitle(title);
        }
        //targetId
        mTargetId = intent.getData().getQueryParameter("targetId");

        isReconnect(getIntent());
    }

    /**
     * 判断消息是否是 push 消息
     */
    private void isReconnect(Intent intent) {
        if (intent == null || intent.getData() == null)
            return;
        //token
        String token = AccountManager.getUserInfo().getObj().getRongCloudToken();

        //push
        if (intent.getData().getScheme().equals("rong") && intent.getData().getQueryParameter("isFromPush") != null) {
            isFromPush = true;
            Log.e("","isFromPush");
            //通过intent.getData().getQueryParameter("push") 为true，判断是否是push消息
            if (intent.getData().getQueryParameter("isFromPush").equals("true")) {
                reconnect(token);
            } else {
                //程序切到后台，收到消息后点击进入,会执行这里
                if (RongIM.getInstance() == null || RongIM.getInstance().getRongIMClient() == null) {
                    reconnect(token);
                } else {
                    enterFragment(mConversationType, mTargetId);
                }
            }
        }
    }

    /**
     * 重连
     *
     * @param token
     */
    private void reconnect(String token) {
        Log.e("", "《重连》");

        if (getApplicationInfo().packageName.equals(OtherUtil.getCurProcessName(getApplicationContext()))) {

            RongIM.connect(token, new RongIMClient.ConnectCallback() {
                @Override
                public void onTokenIncorrect() {
                    Log.e("", "连接失败");
                }

                @Override
                public void onSuccess(String s) {
                    enterFragment(mConversationType, mTargetId);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {
                    Log.e("", "连接失败—————>" + errorCode);
                }
            });
        }
    }

    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType
     * @param mTargetId
     */
    private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        ConversationFragment fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.chat_message_rt);

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();

        fragment.setUri(uri);
    }

    @Override
    public BaseActivity getActivity() {
        return this;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == event.getKeyCode() && isFromPush) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
